package com.uzai.console.service.sysdomain.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.enums.DeviceAuthTypeEnum;
import com.uzai.common.enums.PaymentTypeEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.constant.CacheKey;
import com.uzai.console.dto.alipaydetail.AlipayDetailCreateDto;
import com.uzai.console.dto.sysdomain.*;
import com.uzai.console.dto.sysdomain.sysdomaindetail.SysDomainRebuyDto;
import com.uzai.console.entity.*;
import com.uzai.console.enums.AlipayStatusEnum;
import com.uzai.console.enums.AlipayTypeEnum;
import com.uzai.console.enums.MerAccDetailSourceTypeEnum;
import com.uzai.console.mapper.*;
import com.uzai.console.service.alipaydetail.AlipayDetailService;
import com.uzai.console.service.kuizhan.KuaiZhanService;
import com.uzai.console.service.sysdomain.SysDomainService;
import com.uzai.console.vo.alipaydetail.businessinfo.KuaiZhanDomianBuyBusinessInfo;
import com.uzai.console.vo.alipaydetail.businessinfo.KuaiZhanDomianRebuyBusinessInfo;
import com.uzai.console.vo.kuaizhan.*;
import com.uzai.console.vo.sysdomain.*;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 域名联盟
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class SysDomainServiceImpl implements SysDomainService {

    Logger logger = LoggerFactory.getLogger(SysDomainServiceImpl.class);

    @Autowired
    private SysDomainMapper sysDomainMapper;
    @Autowired
    private KuaiZhanService kuaiZhanService;
    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private AlipayDetailService alipayDetailService;
    @Autowired
    private AlipayDetailMapper alipayDetailMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private MerAccDetailMapper merAccDetailMapper;
    @Autowired
    private SysDomainDetailMapper sysDomainDetailMapper;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询系统快站域名列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sysDomainQuery
     * @return null
     */
    public Page<SysDomainKuaizhanInfoVo> findSysDomainKuaizhanList(SysDomainQuery sysDomainQuery){
        //新建返回到页面的LIST对象
        List<SysDomainKuaizhanInfoVo> sysDomainKuaizhanInfoVoList = new ArrayList<>();
        //执行分页查询对象
        Page<SysDomain> page = new Page<>();
        sysDomainQuery.convert(page);

        int now = DateUtil.getNowTime();

        ArrayList<SysDomain> sysDomainList =  sysDomainMapper.findByList(page, sysDomainQuery);
        if(sysDomainList != null && sysDomainList.size() > 0){
            for (SysDomain sysDomain : sysDomainList){
                SysDomainKuaizhanInfoVo sysDomainKuaizhanInfoVo = new SysDomainKuaizhanInfoVo();
                BeanUtils.copyProperties(sysDomain, sysDomainKuaizhanInfoVo);
                //请求快站域名本月封禁次数
                GetSiteBanCountVo getSiteBanCountVo = kuaiZhanService.getSiteBanCount(sysDomain.getSiteId());
                if(getSiteBanCountVo != null){
                    sysDomainKuaizhanInfoVo.setBanCount(getSiteBanCountVo.getCount());
                }
                //查询缓存中是否存在共享码
                Object object = redisTemplate.opsForValue().get(String.format(CacheKey.SYSDOMAIN_ID_SHARECODE, sysDomain.getId()));
                if(object != null){
                    sysDomainKuaizhanInfoVo.setShareCode((String)object);
                }
                //请求快站域名详情信息获取剩余天数
                try {
                    int packageRemainingDays = 0;
                    GetSiteInfoVo getSiteInfoVo = kuaiZhanService.getSiteInfo(sysDomain.getSiteId());
                    if(getSiteInfoVo != null){
                        packageRemainingDays = Tools.getInteger(getSiteInfoVo.getPackageRemainingDays()).intValue();
                    }
                    int expiredTime = now + packageRemainingDays * 24 * 3600;
                    sysDomainKuaizhanInfoVo.setExpiredTime(expiredTime);
                }catch (Exception e){

                }

                sysDomainKuaizhanInfoVoList.add(sysDomainKuaizhanInfoVo);
            }
        }
        //返回到页面分页对象
        Page<SysDomainKuaizhanInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(sysDomainKuaizhanInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询快站域名价格
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    public SysDomainKuaizhanPriceVo findSysDomainKuaizhanPrice(){
        SysDomainKuaizhanPriceVo sysDomainKuaizhanPriceVo = new SysDomainKuaizhanPriceVo();
        String kz_price_year = sysConfigMapper.selectByKey("kz_price_year");
        if(StringUtils.isNotBlank(kz_price_year)){
            sysDomainKuaizhanPriceVo.setPrice(Double.parseDouble(kz_price_year));
        }
        return sysDomainKuaizhanPriceVo;
    }

    /**
     * 购买系统快站域名
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    @Transactional
    public  BuySysDomainVo buySysDomainKuaizhan(SysDomainBuyDto sysDomainBuyDto){
        //返回对象
        BuySysDomainVo buySysDomainVo = new BuySysDomainVo();
        //业务号
        String trandeno = Tools.getCurrentTimeByFormat("yyyyMMdd") + IdWorker.getIdStr();
        //当前时间
        Integer now = DateUtil.getNowTime();

        if(sysDomainBuyDto.getPayType() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入支付类型");
        }

        //按年购买价格
        SysDomainKuaizhanPriceVo sysDomainKuaizhanPriceVo = findSysDomainKuaizhanPrice();
        if(sysDomainKuaizhanPriceVo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请先设置域名按年购买价格");
        }

        Double price = sysDomainKuaizhanPriceVo.getPrice();
        Double amount = price;
        Integer quantity = 12; //域名按年购买

        //判断支付类型
        if(sysDomainBuyDto.getPayType().intValue() == PaymentTypeEnum.PAY_ALIPAY.getId().intValue()) {//支付宝支付

            //添加支付宝账单
            AlipayDetail alipayDetail = new AlipayDetail();
            alipayDetail.setId(IdWorker.getId());
            alipayDetail.setMerId(sysDomainBuyDto.getMerId());
            alipayDetail.setTradeno(trandeno);
            alipayDetail.setType(AlipayTypeEnum.KUAIZHAN_DOMIAN_BUY.getId()); //快站域名购买
            //业务信息
            KuaiZhanDomianBuyBusinessInfo kuaiZhanDomianBuyBusinessInfo = new KuaiZhanDomianBuyBusinessInfo();
            kuaiZhanDomianBuyBusinessInfo.setAuthType(DeviceAuthTypeEnum.DAT_YEAR.getId()); //按年购买
            kuaiZhanDomianBuyBusinessInfo.setQuantity(quantity);
            kuaiZhanDomianBuyBusinessInfo.setAmount(amount);
            kuaiZhanDomianBuyBusinessInfo.setPrice(price);
            alipayDetail.setBusinessInfo(Tools.getStrEmpty(JSONObject.toJSONString(kuaiZhanDomianBuyBusinessInfo)));
            alipayDetail.setAmount(amount);
            alipayDetail.setStatus(AlipayStatusEnum.WAIT_BUYER_PAY.getId()); //等待付款
            alipayDetail.setCreateTime(now);
            alipayDetail.setUpdateTime(now);

            //请求支付宝申请订单
            AlipayDetailCreateDto alipayDetailCreateDto = new AlipayDetailCreateDto();
            alipayDetailCreateDto.setOutTradeNo(alipayDetail.getTradeno());
            alipayDetailCreateDto.setTotalAmount(alipayDetail.getAmount());
            alipayDetailCreateDto.setSubject(AlipayTypeEnum.KUAIZHAN_DOMIAN_BUY.getDesc());
            String alipayUrl = alipayDetailService.createAlipayDetail(alipayDetailCreateDto);
            if(StringUtils.isNotBlank(alipayUrl)){
                alipayDetail.setAlipayUrl(alipayUrl);
                //插入支付宝账单
                alipayDetailMapper.insertSelective(alipayDetail);

                //返回支付页面
                buySysDomainVo.setAlipayUrl(uzaiConsoleSysConfig.getAlipayPaypageUrl()+"?id=" + alipayDetail.getId());

            }else{
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "调用支付宝失败");
            }
        }else if(sysDomainBuyDto.getPayType().intValue() == PaymentTypeEnum.PAY_BALANCE.getId().intValue()){ //余额支付
            //处理余额支付信息
            //查询账号信息
            Merchant merchant = merchantMapper.selectById(sysDomainBuyDto.getMerId());
            //判断余额大小
            Double balance = merchant.getBalance();
            if(balance.doubleValue() < amount){ //不够支付
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账户余额不足");
            }

            //修改账户余额
            merchant.setBalance(balance-amount);
            merchant.setUpdateTime(now);
            merchantMapper.updateBalance(merchant);

            //添加账户明细
            MerAccDetail merAccDetail = new MerAccDetail();
            merAccDetail.setId(IdWorker.getId());
            merAccDetail.setMerId(merchant.getId());
            merAccDetail.setOperateType(2);//支出
            merAccDetail.setMoney(merchant.getBalance());
            merAccDetail.setCgMoney(amount);
            merAccDetail.setSourceType(MerAccDetailSourceTypeEnum.KUAIZHAN_DOMIAN_BUY.getId());//快站域名购买
            merAccDetail.setTradeno(trandeno);
            merAccDetail.setCreateTime(now);
            merAccDetail.setUpdateTime(now);
            merAccDetailMapper.insert(merAccDetail);

            //随机快站二级域名
            String domain = RandomStringUtils.randomAlphanumeric(10).toLowerCase();
            //判断二级域名是否重复，如果重复则一直随机获取,直到数据库没有这个二级域名为止
            Boolean domainRepeatFlag = true;
            do {
                SysDomain sysDomain_Repeat = sysDomainMapper.selectByDomain(domain, sysDomainBuyDto.getMerId());
                if(sysDomain_Repeat == null){
                    domainRepeatFlag = false;
                }else{
                    domain = RandomStringUtils.randomAlphanumeric(10).toLowerCase();
                }
            }while (domainRepeatFlag);

            //申请创建站点
            CreateSiteVo createSiteVo = kuaiZhanService.createSite(domain);
            if(createSiteVo == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "创建快站域名失败");
            }

            logger.info("---申请站点成功----- createSiteVo={}",JSONObject.toJSONString(createSiteVo));

            SysDomain sysDomain = new SysDomain();
            sysDomain.setId(IdWorker.getId());
            sysDomain.setMerId(sysDomainBuyDto.getMerId());
            sysDomain.setType(1); //快站域名
            sysDomain.setAppKey(sysConfigMapper.selectByKey("kzappkey"));
            sysDomain.setAppSecret(sysConfigMapper.selectByKey("kzappsecret"));
            sysDomain.setSiteId(createSiteVo.getSiteId());
            sysDomain.setSiteName(domain);
            sysDomain.setDomain(domain);
            sysDomain.setSiteDomain("https://" + createSiteVo.getSiteDomain());
            sysDomain.setExpiredTime(now + 31536000);
            sysDomain.setStatus(1);
            sysDomain.setShared(0);
            sysDomain.setCreateTime(now);
            sysDomain.setUpdateTime(now);
            sysDomainMapper.insertSelective(sysDomain);

            logger.info("---插入站点数据成功----- sysDomain={}",JSONObject.toJSONString(sysDomain));

            Integer beginTime = now;  //授权开始时间
            Integer expireTime = sysDomain.getExpiredTime(); //授权到期时间
            //添加快站域名购买明细表
            SysDomainDetail sysDomainDetail = new SysDomainDetail();
            sysDomainDetail.setId(IdWorker.getId());
            sysDomainDetail.setMerId(sysDomainBuyDto.getMerId());
            sysDomainDetail.setDomainId(sysDomain.getId());
            sysDomainDetail.setAuthType(DeviceAuthTypeEnum.DAT_YEAR.getId());
            sysDomainDetail.setQuantity(quantity); //试用为0
            sysDomainDetail.setBeginTime(beginTime);
            sysDomainDetail.setExpireTime(expireTime);
            sysDomainDetail.setPayTime(now);
            sysDomainDetail.setPayType(sysDomainBuyDto.getPayType());
            sysDomainDetail.setTradeno(trandeno);
            sysDomainDetail.setAmount(amount);
            sysDomainDetail.setRemark("余额支付");
            sysDomainDetail.setCreateTime(now);
            sysDomainDetail.setUpdateTime(now);
            sysDomainDetailMapper.insert(sysDomainDetail);

            logger.info("---插入站点支付明细成功----- sysDomainDetail={}",JSONObject.toJSONString(sysDomainDetail));

            //关闭域名Https跳转
            //kuaiZhanService.changeDomainHttpsForward(createSiteVo.getSiteId(), domain, false);
            //开通套餐
            Boolean packageFlag = kuaiZhanService.openBusinessPackage(createSiteVo.getSiteId());

            logger.info("---开通套餐成功-----packageFlag={}", JSONObject.toJSONString(packageFlag));

            //更新快站页面JS和发布
            String content = Tools.getStr(sysConfigMapper.selectByKey("kz_page_js"));
            //更新站点页面JS
            Boolean modifyPageJsFlag = kuaiZhanService.modifyPageJs(createSiteVo.getSiteId(), content);

            logger.info("---更新站点页面JS-----modifyPageJsFlag={}", JSONObject.toJSONString(modifyPageJsFlag));

            //发布快站站点
            PublishSiteVo publishSiteVo = kuaiZhanService.publishSite(createSiteVo.getSiteId());

            logger.info("---发布快站域名----- publishSiteVo={}",JSONObject.toJSONString(publishSiteVo));

            //发布页面
            PublishPageVo publishPageVo = kuaiZhanService.publishPage(createSiteVo.getSiteId());

            logger.info("---发布页面----- publishPageVo={}",JSONObject.toJSONString(publishPageVo));
        }

        return buySysDomainVo;
    }

    /**
     * 快站域名续费
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sysDomainRebuyDto
     * @return null
     */
    @Transactional
    public BuySysDomainVo rebuySysDomainKuaizhan(SysDomainRebuyDto sysDomainRebuyDto){

        //返回对象
        BuySysDomainVo buySysDomainVo = new BuySysDomainVo();
        //业务号
        String trandeno = Tools.getCurrentTimeByFormat("yyyyMMdd") + IdWorker.getIdStr();
        //当前时间
        Integer now = DateUtil.getNowTime();

        if(sysDomainRebuyDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        SysDomain sysDomain = sysDomainMapper.selectById(sysDomainRebuyDto.getId(), sysDomainRebuyDto.getMerId());
        if(sysDomain == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该域名不存在");
        }

        if(sysDomainRebuyDto.getPayType() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入支付类型");
        }

        //按年购买价格
        SysDomainKuaizhanPriceVo sysDomainKuaizhanPriceVo = findSysDomainKuaizhanPrice();
        if(sysDomainKuaizhanPriceVo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请先设置域名按年购买价格");
        }

        Double price = sysDomainKuaizhanPriceVo.getPrice();
        Double amount = price;
        Integer quantity = 12; //域名按年购买

        //判断支付类型
        if(sysDomainRebuyDto.getPayType().intValue() == PaymentTypeEnum.PAY_ALIPAY.getId().intValue()) {//支付宝支付
            //添加支付宝账单
            AlipayDetail alipayDetail = new AlipayDetail();
            alipayDetail.setId(IdWorker.getId());
            alipayDetail.setMerId(sysDomainRebuyDto.getMerId());
            alipayDetail.setTradeno(trandeno);
            alipayDetail.setType(AlipayTypeEnum.KUAIZHAN_DOMIAN_REBUY.getId()); //快站域名续费
            //业务信息
            KuaiZhanDomianRebuyBusinessInfo kuaiZhanDomianRebuyBusinessInfo = new KuaiZhanDomianRebuyBusinessInfo();
            kuaiZhanDomianRebuyBusinessInfo.setDomainId(sysDomain.getId());
            kuaiZhanDomianRebuyBusinessInfo.setAuthType(DeviceAuthTypeEnum.DAT_YEAR.getId()); //按年购买
            kuaiZhanDomianRebuyBusinessInfo.setQuantity(quantity);
            kuaiZhanDomianRebuyBusinessInfo.setAmount(amount);
            kuaiZhanDomianRebuyBusinessInfo.setPrice(price);
            alipayDetail.setBusinessInfo(Tools.getStrEmpty(JSONObject.toJSONString(kuaiZhanDomianRebuyBusinessInfo)));
            alipayDetail.setAmount(amount);
            alipayDetail.setStatus(AlipayStatusEnum.WAIT_BUYER_PAY.getId()); //等待付款
            alipayDetail.setCreateTime(now);
            alipayDetail.setUpdateTime(now);

            //请求支付宝申请订单
            AlipayDetailCreateDto alipayDetailCreateDto = new AlipayDetailCreateDto();
            alipayDetailCreateDto.setOutTradeNo(alipayDetail.getTradeno());
            alipayDetailCreateDto.setTotalAmount(alipayDetail.getAmount());
            alipayDetailCreateDto.setSubject(AlipayTypeEnum.KUAIZHAN_DOMIAN_REBUY.getDesc());
            String alipayUrl = alipayDetailService.createAlipayDetail(alipayDetailCreateDto);
            if(StringUtils.isNotBlank(alipayUrl)){
                alipayDetail.setAlipayUrl(alipayUrl);
                //插入支付宝账单
                alipayDetailMapper.insertSelective(alipayDetail);
                //返回支付页面
                buySysDomainVo.setAlipayUrl(uzaiConsoleSysConfig.getAlipayPaypageUrl()+"?id=" + alipayDetail.getId());
            }else{
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "调用支付宝失败");
            }
        }else if(sysDomainRebuyDto.getPayType().intValue() == PaymentTypeEnum.PAY_BALANCE.getId().intValue()){ //余额支付
            //处理余额支付信息
            //查询账号信息
            Merchant merchant = merchantMapper.selectById(sysDomainRebuyDto.getMerId());
            //判断余额大小
            Double balance = merchant.getBalance();
            if(balance.doubleValue() < amount){ //不够支付
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账户余额不足");
            }

            //修改账户余额
            merchant.setBalance(balance-amount);
            merchant.setUpdateTime(now);
            merchantMapper.updateBalance(merchant);

            //添加账户明细
            MerAccDetail merAccDetail = new MerAccDetail();
            merAccDetail.setId(IdWorker.getId());
            merAccDetail.setMerId(merchant.getId());
            merAccDetail.setOperateType(2);//支出
            merAccDetail.setMoney(merchant.getBalance());
            merAccDetail.setCgMoney(amount);
            merAccDetail.setSourceType(MerAccDetailSourceTypeEnum.KUAIZHAN_DOMIAN_REBUY.getId());//快站域名续费
            merAccDetail.setTradeno(trandeno);
            merAccDetail.setCreateTime(now);
            merAccDetail.setUpdateTime(now);
            merAccDetailMapper.insert(merAccDetail);

            //判断是否是新的APPkey,如果是新的APPkey。则直接续费,否则走购买新新站覆盖旧的域名信息
            String appKey = sysConfigMapper.selectByKey("kzappkey");
            if(appKey.equals(sysDomain.getAppKey())){
                //刷新域名到期时间
                sysDomain.setExpiredTime(sysDomain.getExpiredTime() + 31536000);
                sysDomain.setUpdateTime(now);
                sysDomainMapper.updateByOldSiteId(sysDomain, sysDomain.getSiteId());

                Integer beginTime = now;  //授权开始时间
                //添加快站域名购买明细表
                SysDomainDetail sysDomainDetail = new SysDomainDetail();
                sysDomainDetail.setId(IdWorker.getId());
                sysDomainDetail.setMerId(sysDomain.getMerId());
                sysDomainDetail.setDomainId(sysDomain.getId());
                sysDomainDetail.setAuthType(DeviceAuthTypeEnum.DAT_YEAR.getId());
                sysDomainDetail.setQuantity(quantity); //试用为0
                sysDomainDetail.setBeginTime(beginTime);
                sysDomainDetail.setExpireTime(sysDomain.getExpiredTime());
                sysDomainDetail.setPayTime(now);
                sysDomainDetail.setPayType(sysDomainRebuyDto.getPayType());
                sysDomainDetail.setTradeno(trandeno);
                sysDomainDetail.setAmount(amount);
                sysDomainDetail.setRemark("余额支付");
                sysDomainDetail.setCreateTime(now);
                sysDomainDetail.setUpdateTime(now);
                sysDomainDetailMapper.insert(sysDomainDetail);

                //开通套餐续费
                Boolean packageFlag = kuaiZhanService.openBusinessPackage(sysDomain.getSiteId());
                if(packageFlag){
                    logger.info("---开通套餐成功-----packageFlag={}", JSONObject.toJSONString(packageFlag));
                }else{
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "开通快站域名套餐失败");
                }
            }else{
                //随机快站二级域名
                String domain = RandomStringUtils.randomAlphanumeric(10).toLowerCase();
                //判断二级域名是否重复，如果重复则一直随机获取,直到数据库没有这个二级域名为止
                Boolean domainRepeatFlag = true;
                do {
                    SysDomain sysDomain_Repeat = sysDomainMapper.selectByDomain(domain, sysDomainRebuyDto.getMerId());
                    if(sysDomain_Repeat == null){
                        domainRepeatFlag = false;
                    }else{
                        domain = RandomStringUtils.randomAlphanumeric(10).toLowerCase();
                    }
                }while (domainRepeatFlag);

                //申请创建站点
                CreateSiteVo createSiteVo = kuaiZhanService.createSite(domain);
                if(createSiteVo == null){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "创建快站域名失败");
                }

                logger.info("---申请站点成功----- createSiteVo={}",JSONObject.toJSONString(createSiteVo));

                //把新的站点信息覆盖旧的域名数据
                String oldSiteId  = sysDomain.getSiteId();
                sysDomain.setAppKey(sysConfigMapper.selectByKey("kzappkey"));
                sysDomain.setAppSecret(sysConfigMapper.selectByKey("kzappsecret"));
                sysDomain.setSiteId(createSiteVo.getSiteId());
                sysDomain.setSiteName(domain);
                sysDomain.setDomain(domain);
                sysDomain.setSiteDomain("https://" + createSiteVo.getSiteDomain());
                sysDomain.setExpiredTime(now + 31536000);
                sysDomain.setUpdateTime(now);
                sysDomainMapper.updateByOldSiteId(sysDomain, oldSiteId);

                logger.info("---插入站点数据成功----- sysDomain={}",JSONObject.toJSONString(sysDomain));

                Integer beginTime = now;  //授权开始时间
                Integer expireTime = sysDomain.getExpiredTime(); //授权到期时间
                //添加快站域名购买明细表
                SysDomainDetail sysDomainDetail = new SysDomainDetail();
                sysDomainDetail.setId(IdWorker.getId());
                sysDomainDetail.setMerId(sysDomainRebuyDto.getMerId());
                sysDomainDetail.setDomainId(sysDomain.getId());
                sysDomainDetail.setAuthType(DeviceAuthTypeEnum.DAT_YEAR.getId());
                sysDomainDetail.setQuantity(quantity); //试用为0
                sysDomainDetail.setBeginTime(beginTime);
                sysDomainDetail.setExpireTime(expireTime);
                sysDomainDetail.setPayTime(now);
                sysDomainDetail.setPayType(sysDomainRebuyDto.getPayType());
                sysDomainDetail.setTradeno(trandeno);
                sysDomainDetail.setAmount(amount);
                sysDomainDetail.setRemark("余额支付");
                sysDomainDetail.setCreateTime(now);
                sysDomainDetail.setUpdateTime(now);
                sysDomainDetailMapper.insert(sysDomainDetail);

                logger.info("---插入站点支付明细成功----- sysDomainDetail={}",JSONObject.toJSONString(sysDomainDetail));

                //关闭域名Https跳转
                //kuaiZhanService.changeDomainHttpsForward(createSiteVo.getSiteId(), domain, false);
                //开通套餐
                Boolean packageFlag = kuaiZhanService.openBusinessPackage(createSiteVo.getSiteId());

                logger.info("---开通套餐成功-----packageFlag={}", JSONObject.toJSONString(packageFlag));

                //更新快站页面JS和发布
                String content = Tools.getStr(sysConfigMapper.selectByKey("kz_page_js"));
                //更新站点页面JS
                Boolean modifyPageJsFlag = kuaiZhanService.modifyPageJs(createSiteVo.getSiteId(), content);

                logger.info("---更新站点页面JS-----modifyPageJsFlag={}", JSONObject.toJSONString(modifyPageJsFlag));

                //发布快站站点
                PublishSiteVo publishSiteVo = kuaiZhanService.publishSite(createSiteVo.getSiteId());

                logger.info("---发布快站域名----- publishSiteVo={}",JSONObject.toJSONString(publishSiteVo));

                //发布页面
                PublishPageVo publishPageVo = kuaiZhanService.publishPage(createSiteVo.getSiteId());

                logger.info("---发布页面----- publishPageVo={}",JSONObject.toJSONString(publishPageVo));
            }
        }

        return buySysDomainVo;

    }

    /**
     * 查询系统快站域名详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sysDomainIdDto
     * @return null
     */
    public SysDomainKuaizhanInfoVo findSysDomainKuaizhanInfo(SysDomainIdDto sysDomainIdDto){
        if(sysDomainIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }
        SysDomain sysDomain = sysDomainMapper.selectById(sysDomainIdDto.getId(), sysDomainIdDto.getMerId());

        if(sysDomain == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该域名不存在");
        }
        SysDomainKuaizhanInfoVo sysDomainKuaizhanInfoVo = new SysDomainKuaizhanInfoVo();

        BeanUtils.copyProperties(sysDomain, sysDomainKuaizhanInfoVo);

        //请求快站域名本月封禁次数
        GetSiteBanCountVo getSiteBanCountVo = kuaiZhanService.getSiteBanCount(sysDomain.getSiteId());
        if(getSiteBanCountVo != null){
            sysDomainKuaizhanInfoVo.setBanCount(getSiteBanCountVo.getCount());
        }

        return sysDomainKuaizhanInfoVo;
    }

    /**
     * 编辑系统快站域名
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sysDomainKuaizhanDto
     * @return null
     */
    public void updateSysDomainKuaizhan(SysDomainKuaizhanDto sysDomainKuaizhanDto){
        if(sysDomainKuaizhanDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }
        SysDomain sysDomain = sysDomainMapper.selectById(sysDomainKuaizhanDto.getId(), sysDomainKuaizhanDto.getMerId());

        if(sysDomain == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该域名id不存在");
        }

        if(Tools.getInteger(sysDomain.getShared()).intValue() != 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只能编辑私有快站域名");
        }

        //修改二级域名
        if(StringUtils.isNotBlank(sysDomainKuaizhanDto.getDomain())){
            if(!sysDomainKuaizhanDto.getDomain().equals(sysDomain.getDomain())){
                SysDomain sysDomain_Repeat = sysDomainMapper.selectByDomain(sysDomainKuaizhanDto.getDomain(), sysDomainKuaizhanDto.getMerId());
                if(sysDomain_Repeat != null){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该二级域名已经存在");
                }
                ChangeDomainVo changeDomainVo = kuaiZhanService.changeDomain(sysDomain.getSiteId(), sysDomainKuaizhanDto.getDomain());
                if(changeDomainVo == null){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改域名失败");
                }
                sysDomain.setDomain(sysDomainKuaizhanDto.getDomain());
                sysDomain.setSiteDomain("https://"+changeDomainVo.getNewdomain());
            }
        }

        //修改站点名称
        String siteName = Tools.getStr(sysDomainKuaizhanDto.getSiteName());
        if(StringUtils.isNotBlank(siteName)){
            if(!siteName.equals(sysDomain.getSiteName())){
                Boolean flag = kuaiZhanService.updateSiteSetting(sysDomain.getSiteId(), siteName);
                if(flag){
                    sysDomain.setSiteName(siteName);
                }else{
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改站点名称失败");
                }

            }
        }
        sysDomain.setRemark(sysDomainKuaizhanDto.getRemark());
        sysDomainMapper.updateBySiteId(sysDomain);
    }

    /**
     * 检测快站域名是否封禁
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sysDomainIdDto
     * @return null
     */
    public CheckDomainBanVo checkSysDomainKuaizhan(SysDomainIdDto sysDomainIdDto){
        if(sysDomainIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }
        SysDomain sysDomain = sysDomainMapper.selectById(sysDomainIdDto.getId(), sysDomainIdDto.getMerId());

        if(sysDomain == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该域名不存在");
        }

        //验证的时候带上域名
        String domain = sysDomain.getDomain() + ".kuaizhan.com";

        CheckDomainBanVo checkDomainBanVo = kuaiZhanService.checkDomainBan(domain);

        if(checkDomainBanVo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "检测失败");
        }
        return checkDomainBanVo;
    }

    /**
     * 生成快站域名共享码
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sysDomainIdDto
     * @return null
     */
    public CreateSharedCodeVo createShareCode(SysDomainIdDto sysDomainIdDto){

        CreateSharedCodeVo createSharedCodeVo = new CreateSharedCodeVo();

        if(sysDomainIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }
        SysDomain sysDomain = sysDomainMapper.selectById(sysDomainIdDto.getId(), sysDomainIdDto.getMerId());

        if(sysDomain == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该域名不存在");
        }

        //生成随机15位共享码
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        char[] arrayPass= str.toCharArray();
        String shareCode = Tools.getRandomPass(15, arrayPass);
        redisTemplate.opsForValue().set(String.format(CacheKey.SYSDOMAIN_ID_SHARECODE, sysDomain.getId()), shareCode, 3, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(String.format(CacheKey.SYSDOMAIN_SHARE_CODE_ID, shareCode), sysDomain.getId() + "_" + sysDomain.getMerId(), 3, TimeUnit.MINUTES);

        createSharedCodeVo.setShareCode(shareCode);

        return createSharedCodeVo;
    }

    /**
     * 通过共享码添加快站域名
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sysDomainShareCodeDto
     * @return null
     */
    public void addSysDomainByShareCode(SysDomainShareCodeDto sysDomainShareCodeDto){
        if(StringUtils.isBlank(sysDomainShareCodeDto.getShareCode())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "共享码不能为空");
        }

        //查询缓存中是否存在共享码
        Object object = redisTemplate.opsForValue().get(String.format(CacheKey.SYSDOMAIN_SHARE_CODE_ID, sysDomainShareCodeDto.getShareCode()));
        if(object == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该共享码不正确或者已经失效");
        }
        String val = (String)object;

        if(StringUtils.isBlank(val)){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该共享码不正确或者已经失效");
        }

        String[] valArray = val.split("_");

        if(valArray == null || valArray.length != 2){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该共享码对应的缓存值格式不正确");
        }
        SysDomain sysDomain = sysDomainMapper.selectById(Long.valueOf(valArray[0]), Long.valueOf(valArray[1]));
        if(sysDomain == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该共享码对应的域名不存在");
        }

        Long merId_old = sysDomain.getMerId();

        SysDomain sysDomain_new = sysDomainMapper.selectByDomain(sysDomain.getDomain(), sysDomainShareCodeDto.getMerId());
        if(sysDomain_new != null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该域名已经存在");
        }

        int now = DateUtil.getNowTime();
        sysDomain.setId(IdWorker.getId());
        sysDomain.setMerId(sysDomainShareCodeDto.getMerId());
        sysDomain.setCreateTime(now);
        sysDomain.setUpdateTime(now);
        sysDomain.setShared(1);
        sysDomain.setRemark("从运营商：" + merId_old + "共享的。");
        sysDomainMapper.insertSelective(sysDomain);
    }

    /**
     * 查询系统自用域名列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sysDomainQuery
     * @return null
     */
    public Page<SysDomainPrivateInfoVo> findSysDomainPrivateList(SysDomainQuery sysDomainQuery){
        //新建返回到页面的LIST对象
        List<SysDomainPrivateInfoVo> sysDomainPrivateInfoVoArrayList = new ArrayList<>();

        //执行分页查询对象
        Page<SysDomain> page = new Page<>();
        sysDomainQuery.convert(page);
        ArrayList<SysDomain> sysDomainList =  sysDomainMapper.findByList(page, sysDomainQuery);
        if(sysDomainList != null && sysDomainList.size() > 0){
            for (SysDomain sysDomain : sysDomainList){
                SysDomainPrivateInfoVo sysDomainPrivateInfoVo = new SysDomainPrivateInfoVo();
                BeanUtils.copyProperties(sysDomain, sysDomainPrivateInfoVo);
                sysDomainPrivateInfoVoArrayList.add(sysDomainPrivateInfoVo);
            }
        }
        //返回到页面分页对象
        Page<SysDomainPrivateInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(sysDomainPrivateInfoVoArrayList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 添加系统自用域名
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sysDomainPrivateDto
     * @return null
     */
    public void addSysDomainPrivate(SysDomainPrivateDto sysDomainPrivateDto){

        if(StringUtils.isBlank(sysDomainPrivateDto.getSiteDomain())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入域名");
        }

        if(!sysDomainPrivateDto.getSiteDomain().contains("http://") && !sysDomainPrivateDto.getSiteDomain().contains("https://") ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "域名开头必须是https://或http://");
        }

        SysDomain sysDomain = sysDomainMapper.selectBySiteDomain(sysDomainPrivateDto.getSiteDomain(), sysDomainPrivateDto.getMerId());
        if(sysDomain != null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该域名已经存在");
        }
        sysDomain = new SysDomain();
        Integer now = DateUtil.getNowTime();
        sysDomain.setId(IdWorker.getId());
        sysDomain.setMerId(sysDomainPrivateDto.getMerId());
        sysDomain.setType(2);
        sysDomain.setStatus(sysDomainPrivateDto.getStatus());
        sysDomain.setSiteDomain(sysDomainPrivateDto.getSiteDomain());
        sysDomain.setRemark(sysDomainPrivateDto.getRemark());
        sysDomain.setCreateTime(now);
        sysDomain.setUpdateTime(now);
        sysDomain.setShared(0);
        sysDomainMapper.insertSelective(sysDomain);
    }

    /**
     * 查询系统自用域名详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sysDomainIdDto
     * @return null
     */
    public SysDomainPrivateInfoVo findSysDomainPrivateInfo(SysDomainIdDto sysDomainIdDto){
        if(sysDomainIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }
        SysDomain sysDomain = sysDomainMapper.selectById(sysDomainIdDto.getId(), sysDomainIdDto.getMerId());

        if(sysDomain == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该域名不存在");
        }
        SysDomainPrivateInfoVo sysDomainPrivateInfoVo = new SysDomainPrivateInfoVo();
        BeanUtils.copyProperties(sysDomain, sysDomainPrivateInfoVo);
        return sysDomainPrivateInfoVo;
    }

    /**
     * 修改系统自用域名
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sysDomainPrivateDto
     * @return null
     */
    public void updateSysDomainPrivate(SysDomainPrivateDto sysDomainPrivateDto){
        if(sysDomainPrivateDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }
        SysDomain sysDomain = sysDomainMapper.selectById(sysDomainPrivateDto.getId(), sysDomainPrivateDto.getMerId());

        if(sysDomain == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该域名不存在");
        }

        if(StringUtils.isBlank(sysDomainPrivateDto.getSiteDomain())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入域名");
        }

        if(!sysDomainPrivateDto.getSiteDomain().contains("http://") && !sysDomainPrivateDto.getSiteDomain().contains("https://") ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "域名开头必须是https://或http://");
        }

        if(!sysDomainPrivateDto.getSiteDomain().equals(sysDomain.getSiteDomain())){
            SysDomain sysDomain_repeat = sysDomainMapper.selectBySiteDomain(sysDomainPrivateDto.getSiteDomain(), sysDomainPrivateDto.getMerId());
            if(sysDomain_repeat != null && sysDomain_repeat.getId().longValue() != sysDomainPrivateDto.getId().longValue()){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新域名已经存在");
            }
        }
        sysDomain.setRemark(sysDomainPrivateDto.getRemark());
        sysDomain.setSiteDomain(sysDomainPrivateDto.getSiteDomain());
        sysDomain.setStatus(sysDomainPrivateDto.getStatus());
        sysDomain.setUpdateTime(DateUtil.getNowTime());
        sysDomainMapper.updateByIdSelective(sysDomain);
    }

    /**
     * 删除
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sysDomainIdDto
     * @return null
     */
    public void deleteSysDomain(SysDomainIdDto sysDomainIdDto){
        if(sysDomainIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }
        sysDomainMapper.deleteById(sysDomainIdDto.getId(), sysDomainIdDto.getMerId());
    }

    /**
     * 下载源码
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param response
     * @return null
     */
    public void downloadSourceCode(HttpServletResponse response){
        File file = new File(uzaiConsoleSysConfig.getDownloadCmsPath());

        if (!file.exists()) {
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "源代码不存在");
        }
        response.setContentType("application/force-download");
        response.addHeader("Content-Disposition", "attachment;fileName=" + file.getName());

        byte[] buffer = new byte[1024];
        try (FileInputStream fis = new FileInputStream(file);
             BufferedInputStream bis = new BufferedInputStream(fis)) {
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        }catch (Exception e){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "下载失败");
        }
    }

    /**
     * 获取下载源码URL
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param
     * @return null
     */
    public SourceCodeDownloadUrl getDownloadSourceCodeUrl(){
        SourceCodeDownloadUrl sourceCodeDownloadUrl = new SourceCodeDownloadUrl();
        sourceCodeDownloadUrl.setCmsSorcecodePath(uzaiConsoleSysConfig.getDownloadCmsPath());
        sourceCodeDownloadUrl.setMiddlePageSorcecodePath(uzaiConsoleSysConfig.getDownloadMiddlepagePath());
        return sourceCodeDownloadUrl;
    }

    /**
     * 获取随机二维码
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    public RandomDomainVo getRandomDomain(){
        RandomDomainVo randomDomainVo = new RandomDomainVo();
        randomDomainVo.setDomain(RandomStringUtils.randomAlphanumeric(10).toLowerCase());
        return randomDomainVo;
    }

    @Override
    public SysDomain getById(Long merId, Long domainId) {
        return sysDomainMapper.selectById(domainId, merId);
    }
}
